--- 模块功能：MQTT客户端数据发送处理
-- @author openLuat
-- @module mqtt.mqttOutMsg
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28

module(...,package.seeall)
require"public"

--串口配置
local UART_ID = 1 --uart1
local uartReadData = "";
local uartReadDataFlage = false;


--数据发送的消息队列
local msgQueue = {}


--移除数组里面的消息
function unInit()
    while #msgQueue>0 do
        local outMsg = table.remove(msgQueue,1)
    end
end

--- MQTT客户端是否有数据等待发送
-- @return 有数据等待发送返回true，否则返回false
-- @usage mqttOutMsg.waitForSend()
function waitForSend()
    return #msgQueue > 0
end

--- MQTT客户端数据发送处理
-- @param mqttClient，MQTT客户端对象
-- @return 处理成功返回true，处理出错返回false
-- @usage mqttOutMsg.proc(mqttClient)
function proc(mqttClient)
    while #msgQueue>0 do
        local outMsg = table.remove(msgQueue,1)
        local result = mqttClient:publish(outMsg.t,outMsg.p,outMsg.q)
        if not result then return end 
    end
    return true
end



--定时器空闲中断检测(串口空闲接收数据)
local TimerFunc4Cnt = 0;
local function TimerFunc4()
    if  uartReadDataFlage == true then
        TimerFunc4Cnt = TimerFunc4Cnt+1;
        if  TimerFunc4Cnt >= 20 then
            TimerFunc4Cnt=0;
            uartReadDataFlage = false;
			if  public.imei ~= nil  and  #msgQueue == 0  then
			    table.insert(msgQueue,{t="device/"..public.imei,p=uartReadData,q=0})
			end
            
            uartReadData = "";
        end
    end
end
sys.timerLoopStart(TimerFunc4,10)



--读取串口接收到的数据
local uartdata = ""
local function read()
    uartdata = ""
    while true do
        uartdata = uart.read(UART_ID,"*l",0)
        if not uartdata or string.len(uartdata) == 0 then break end
        uartReadData = uartReadData..uartdata;
        uartReadDataFlage = true
        TimerFunc4Cnt = 0;
    end
end


uart.on(UART_ID,"receive",read)
--配置并且打开串口
uart.setup(UART_ID,115200,8,uart.PAR_NONE,uart.STOP_1)




